﻿using H2.NET.Business;
using H2.NET.Common;
using H2.NET.Data.Common;
using H2.NET.TaskRob;
using H2.NET.Web.Management.Config.Service;
using H2.NET.Web.Pages.SMD.Helper;
using H2.NET.Web.Pages.SMD.Model;
using H2.NET.Web.Pages.SMD.Service;
using H2.NET.Web.Workflow.DwzCode;
using H2.NET.Web.Workflow.Helper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Linq;

namespace H2.NET.Web.Pages.SMD
{
    public partial class DegradeStore : BasePage
    {
        private int _storeid = 0;
        public List<t_smd_Device> Devices = new List<t_smd_Device>();
        public string IsDown = "";
        public bool hasDevice = false;
        public string step;
        protected void Page_Load(object sender, EventArgs e)
        {
            DwzAssessment1.Category = "DegradeStore";
            _storeid = TaskAPI.GetStoreId("storeid");
            if (_storeid != 0)
            {
                Devices = DeviceService.FindEnabledDevice(_storeid);
                rpt_devices.DataSource = Devices;
                rpt_devices.DataBind();
            }

            if (Devices.Count == 0)
            {
                deviceInfo.Visible = false;
            }
            else
            {
                hasDevice = true;
            }

            if (!IsPostBack)
            {
                if (ReadOnly()) return;

                if (IsOverFlow)
                {
                    btn_submit.Visible = false;
                    JsTip(string.Format("该表单正在被“{0}”处理，请稍后再试。", RobUser));
                    return;
                }

                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");

                var assIds = AssessmentService.GetIdsByTaskApi(TaskAPI);
                step = TaskAPI.Step;

                var storeMasterData = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                if (storeMasterData == null)
                {
                    btn_submit.Visible = false;
                    JsTip("加载数据失败，请关闭页面重新打开！");
                    return;
                }

                if (storeMasterData.NewFitment.Contains("关店"))
                {
                    gb.Visible = true;
                    jj.Visible = false;
                    l_IsDowngraded.Text = "关店";
                }
                else
                {
                    gb.Visible = true;
                    jj.Visible = true;
                    l_IsDowngraded.Text = "降级";
                    IsDown = "Downgraded";
                }

                hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                hl_ExportPdf.Visible = true;

                if (storeMasterData.SubmitDate != null)
                    uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");

                var store = StoreService.GetSmdStoreById(_storeid);
                store.NewFitment = storeMasterData.NewFitment;

                uc_store_info1.store = store;
                uc_store_info1.IsCanEditAuthID = false;
                uc_change_field1.AssessmentIDs = assIds;

                if (TaskAPI.Step == "Data Check" || TaskAPI.Step == "Manager Approve")
                {
                    IsChangeStore.Enabled = true;
                }

                ViewData(store, assIds);

                if (!string.IsNullOrEmpty(storeMasterData.PcModel))
                {
                    IsChangeStore.Checked = storeMasterData.PcModel.Equals("True");
                }


                if (String.IsNullOrEmpty(TaskAPI.GetVariableBySingleValue("Checked")))
                {
                    assessment.Visible = false;
                }

                #region 审批项初始化
                switch (TaskAPI.Step)
                {
                    case "Data Check":
                        assessment.Visible = false;
                        break;
                    case "Manager Approve":
                        break;
                    case "DMO Commit":
                        DwzAssessment1.Category = null;
                        break;
                }
                #endregion
            }
        }


        #region 只读表单

        private bool ReadOnly()
        {
            if (AksRequest.GetString("readonly") == "1")
            {
                // 只读表单，释放抢占
                OpenTasksInstance.OpenTasks.SetTaskClose(TaskAPI.Process, TaskAPI.Incident, TaskAPI.Step);

                assessment.Visible = true;
                btn_submit.Visible = false;
                ajaxUpload1.AllowUpload = false;
                ajaxUpload1.AllowDelete = false;
                DwzAssessment1.Visible = false;

                var storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);
                if (storeMasterData == null)
                {
                    JsTip("该流程还没有提交过，没有任何数据！");
                    return true;
                }

                uc_head1.applicationNo = TaskAPI.GetVariableBySingleValue("ApplicationNo");
                uc_head1.applicatorName = TaskAPI.GetVariableBySingleValue("ApplicatorName");
                uc_head1.date = storeMasterData.SubmitDate.Value.ToString("yyyy-MM-dd");

                var ass = AssessmentService.GetBySubmitData(TaskAPI.Process, TaskAPI.Incident);
                var assIds = AssessmentService.GetIdsByTaskApi(TaskAPI);
                var store = StoreService.GetSmdStoreById(storeMasterData == null ? 0 : storeMasterData.StoreId.Value);
                store.NewFitment = storeMasterData.NewFitment;

                uc_store_info1.store = store;
                uc_store_info1.IsCanEditAuthID = false;
                uc_change_field1.AssessmentIDs = assIds;
                IsChangeStore.Enabled = false;
                IsDown = storeMasterData.RequestRemark;
                IsChangeStore.Checked = storeMasterData.PcModel.Equals("True");
                ViewData(store, assIds);

                hl_ExportPdf.NavigateUrl = "~/Tools/ExportPdf.ashx?taskid=" + TaskAPI.TaskID + "&filename=" + uc_head1.applicationNo + ".pdf";
                hl_ExportPdf.Visible = true;
                btn_print.Visible = true;

                return true;
            }

            return false;
        }
        #endregion

        private bool Send(ref string return_msg)
        {
            bool flag = false;
            try
            {
                var dealer = DealerService.GetById(uc_store_info1.store.DealerID.Value);
                var _store = uc_store_info1.store;
                var summary = "|" + _store.AuthID + "|" + dealer.DealerCode;
                var _storeMasterData = StoreMasterDataService.GetByTaskAPI(TaskAPI);

                #region 数据验证
                if (TaskAPI.Step == "Submit Data" && _storeMasterData.NewFitment.Contains("降级") && IsChangeStore.Checked == false && !uc_store_info1.store.StoreType.Contains("IS"))
                {
                    return_msg = "门店降级需要修改门店基本信息";
                    return false;
                }

                if (DwzAssessment1.Assessment.Opinion != "0" || DwzAssessment1.Assessment.Opinion != "2")
                {
                    if (Devices.Count > 0 && (_storeMasterData.NewFitment.Contains("关店") || l_IsDowngraded.Text == @"关闭"))
                    {
                        JsTip(string.Format("系统检测到，该门店有正在使用中的设备，请通知相关人员处理设备。"));
                        DeviceError.Visible = true;
                        return false;
                    }
                    if (DwzAssessment1.Assessment.Opinion == "1" && (_storeMasterData.NewFitment.Contains("降级") || l_IsDowngraded.Text == @"降级"))
                    {
                        if (string.IsNullOrEmpty(uc_store_info1.store.StoreType))
                        {
                            return_msg = "对不起，门店降级类型不能为空";
                            return false;
                        }
                        if (StoreService.GetStoreTypeCode(uc_store_info1.store.StoreType) ==
                            StoreService.GetStoreTypeCode(l_BeforeDowngradedType.Text))
                        {
                            return_msg = "对不起，门店降级类型不能选择一样的";
                            return false;
                        }
                    }
                }
                if (DwzAssessment1.Assessment.Remark == "")
                {
                    if (DwzAssessment1.Assessment.Opinion == "2")
                    {
                        return_msg = "如果驳回此流程,请在状态备注中填写放弃流程的原因";
                        return false;
                    }
                    if (DwzAssessment1.Assessment.Opinion == "0")
                    {
                        return_msg = "如果退回此流程,请在状态备注中填写退回的原因";
                        return false;
                    }
                }

                #endregion

                #region 引擎传值
                TaskAPI["TaskID"] = TaskAPI.TaskID;
                if (TaskAPI.Step == "Submit Data")
                {
                    TaskAPI["BlankVlue"] = _storeid;
                    TaskAPI["Remark_by_Initiator"] = DwzAssessment1.Assessment.Remark;
                    TaskAPI.Summary = "门店关闭or降级区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                    TaskAPI["MailSubject"] = string.Format("经销商 {0}  授权号{1} -- {2}", dealer.DealerCode, _store.AuthID, _store.StoreType);

                }
                else
                {
                    if (TaskAPI.Step == "Data Check")
                    {
                        TaskAPI["Checked"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "1")
                            TaskAPI.Summary = "门店关闭or降级CSM审核/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                        else
                            TaskAPI.Summary = "(退回)登记门店关闭or降级/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;

                    }
                    else if (TaskAPI.Step == "Manager Approve")
                    {
                        TaskAPI["Approved"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "1")
                            TaskAPI.Summary = "门店关闭or降级DMO导入核查/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                        else
                            TaskAPI.Summary = "(退回)门店关闭or降级区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                    }
                    else if (TaskAPI.Step == "DMO Commit")
                    {
                        TaskAPI["Commited"] = DwzAssessment1.Assessment.Opinion;
                        if (DwzAssessment1.Assessment.Opinion == "0")
                        {
                            TaskAPI.Summary = "(退回)门店关闭or降级CSM审核/" + TaskHelper.getSummary(TaskAPI.Summary) + summary;
                        }
                    }
                }

                #endregion

                #region 提交步骤
                string step = string.Empty;
                var key = TaskAPI.GetVariableBySingleValue("AutoBusinessKey");
                Storage.TransactionExecute(o =>
                {
                    #region 审批意见

                    t_Assessment ass = DwzAssessment1.Assessment;
                    var lastAss = (t_Assessment.incident == TaskAPI.Incident & t_Assessment.process == TaskAPI.Process).ListFirst<t_Assessment>("time desc");
                    if ((lastAss != null && lastAss.Step != TaskAPI.Step) || lastAss == null)
                    {
                        Storage.Save(Storage.Context1, ass);
                    }
                    else
                    {
                        Logging.GetLogger().Info("=================表单已重复提交======================");
                        Logging.GetLogger().Info("TaskAPI.TaskID:" + TaskAPI.TaskID);
                        Logging.GetLogger().Info("Incident:" + TaskAPI.Incident);
                        Logging.GetLogger().Info("Process:" + TaskAPI.Process);
                        Logging.GetLogger().Info("TaskAPI.Step:" + TaskAPI.Step);
                        Logging.GetLogger().Info("TaskAPI.UserFullName:" + TaskAPI.UserFullName);
                        Logging.GetLogger().Info("时间：" + DateTime.Now);
                        Logging.GetLogger().Info("UserAPI.UserName:" + UserAPI.UserName);
                        Logging.GetLogger().Info("======================================================");
                        throw new Exception("该表单的步骤已经提交过了，请联系IT。");
                    }

                    #endregion

                    #region “Submit Data”步骤
                    if (TaskAPI.Step == "Submit Data")
                    {
                        // 是否发起修改门店基本信息
                        _storeMasterData.PcModel = IsChangeStore.Checked.ToString();
                        Storage.Save(Storage.Context1, _storeMasterData);

                        if (TaskAPI.Summary.Contains("退回"))
                        {
                            TaskAPI.Summary = "门店关闭or降级区域负责人确认/" + TaskHelper.getSummary(TaskAPI.Summary) + " - " + ass.BusinessKey + summary;
                        }
                    }
                    #endregion

                    #region “Data Check”步骤
                    if (TaskAPI.Step == "Data Check")
                    {
                        // 是否发起修改门店基本信息
                        _storeMasterData.PcModel = IsChangeStore.Checked.ToString();
                        Storage.Save(Storage.Context1, _storeMasterData);
                    }
                    #endregion

                    #region “Manager Approve”步骤
                    if (TaskAPI.Step == "Manager Approve")
                    {
                        if (DwzAssessment1.Assessment.Opinion == "2")
                        {
                            flag = TaskHelper.Abort(TaskAPI.TaskID, DwzAssessment1.Assessment.Remark, TaskAPI.GetVariableBySingleValue("Applicator"));
                            BusinessService.SaveChildProcess(TaskAPI, ass, "abort", DwzAssessment1.Assessment.Remark, DwzAssessment1.Assessment.Time, ass.UserFullName);
                        }

                        // 是否发起修改门店基本信息
                        _storeMasterData.PcModel = IsChangeStore.Checked.ToString();
                        Storage.Save(Storage.Context1, _storeMasterData);
                    }
                    #endregion

                    #region “DMO Commit”步骤
                    if (TaskAPI.Step == "DMO Commit")
                    {
                        if (DwzAssessment1.Assessment.Opinion == "1")
                        {
                            // 将变更日志转移至smd数据库
                            var smd_changelogs = ChangeLogService.McdToSmd(AssessmentService.GetIdsByTaskApi(TaskAPI));
                            Storage.Save(Storage.Context3, smd_changelogs.ToArray());

                            // 获取业务数据主键
                            var id = smd_changelogs[0].DataID;
                            // 获取原始门店数据
                            t_smd_Store store = (t_smd_Store._StoreID == id).ListFirst<t_smd_Store>(Storage.Context3);
                            // 根据变更日志重新加载门店信息
                            DataHelper<t_smd_Store>.Reload(store, smd_changelogs);
                            // 更新门店信息
                            store.StoreReportStatus = store.StoreStatus;
                            Storage.Save(Storage.Context3, store);
                            // 更新业务数据状态
                            StoreMasterDataService.UpdateFinish(TaskAPI);
                            step = "Finish";
                            BusinessService.saveProcessRelation(TaskAPI, ass, store, null, null, null, null, null, null);
                            #region Add By Chris 20170802
                            var masterStore = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                            BusinessService.SaveSycnMappingOrBusinesskey("0", "0", masterStore.BusinessKey);
                            #endregion
                        }
                        else
                        {
                            if (DwzAssessment1.Assessment.Opinion == "2")
                            {
                                flag = TaskHelper.Abort(TaskAPI.TaskID, DwzAssessment1.Assessment.Remark, TaskAPI.GetVariableBySingleValue("Applicator"));
                                BusinessService.SaveChildProcess(TaskAPI, ass, "abort", DwzAssessment1.Assessment.Remark, DwzAssessment1.Assessment.Time, ass.UserFullName);
                            }
                        }
                    }
                    #endregion
                });

                if (DwzAssessment1.Assessment.Opinion != "2")
                {
                    // 变更列表
                    TaskAPI["Content"] = ChangeLogService.GenerateExcel(TaskAPI);
                    flag = TaskAPI.Send();
                }

                //如果数据库写入成功且流程发起成功的情况，将业务表数据与流程实例号进行关联
                if (TaskAPI.Step == "Submit Data")
                {
                    (t_Assessment.process == TaskAPI.Process & t_Assessment.incident == 0 & t_Assessment.assignedToUserName == UserAPI.UserName).Edit<t_Assessment>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });

                    (t_Attachment.process == TaskAPI.Process & t_Attachment.incident == 0 & t_Attachment.username == UserAPI.UserName).Edit<t_Attachment>(p =>
                    {
                        p.Incident = TaskAPI.Incident;
                    });
                }
                else
                {
                    var storeMasterData = StoreMasterDataService.GetByPI(TaskAPI.Process, TaskAPI.Incident);
                    if (step == "Finish")
                    {
                        BusinessService.SaveChildProcess(TaskAPI, DwzAssessment1.Assessment, "Finish");
                        if (!string.IsNullOrEmpty(key) && key == Constant.PROCESS_CHANGELEVEL)
                        {
                            #region 自动启门店基本信息变更流程
                            if (storeMasterData.PcModel == "True")
                            {
                                TaskAPI taskAPI = new TaskAPI(TaskHelper.STORE_DATA_CHANGE_TASKID);
                                string applicationNo = GenerateApplicationNo(taskAPI);

                                taskAPI["AutoBusinessKey"] = Constant.PROCESS_CHANGELEVEL;
                                taskAPI["BlankVlue"] = storeMasterData.StoreId;
                                taskAPI["Actions"] = "ChangeStore";
                                taskAPI.InitAutoTask(applicationNo);
                                taskAPI.Summary = "提交基本信息变更数据/" + TaskHelper.getSummary(TaskAPI.Summary);
                                taskAPI["Region"] = storeMasterData.AreaName;
                                taskAPI["ParentProcess"] = TaskAPI.Process;
                                taskAPI["ParentIncident"] = TaskAPI.Incident;
                                taskAPI["Province"] = storeMasterData.ProvinceName;
                                taskAPI["Category"] = "Store";
                                taskAPI.SetStoreDataChangeRecipient(storeMasterData.AreaName, storeMasterData.ProvinceName, "Store");


                                if (taskAPI.Send())
                                {
                                    var ass = taskAPI.InitAutoAssessment();

                                    Storage.Save(Storage.Context1, ass);

                                    BusinessService.SaveChildProcess(taskAPI, ass, "active");
                                }
                            }
                            #endregion

                            #region 自动发起合同主数据变更
                            if (!storeMasterData.NewFitment.Contains("降级") && !storeMasterData.NewFitment.Contains("关店")) //2016-11-28 Add 降级、关闭 都无需发起合同流程
                            {
                                //if (storeMasterData.RequestRemark == "Downgraded" && storeMasterData.Address == "IS") return true;

                                // 原店面合同
                                var taskContractAPI = new TaskAPI(TaskHelper.STORE_DATA_CHANGE_TASKID);
                                var contractApplicationNo = GenerateApplicationNo(taskContractAPI);
                                var store = StoreService.GetSmdStoreById(storeMasterData.StoreId.Value);

                                taskContractAPI["ParentProcess"] = TaskAPI.Process;
                                taskContractAPI["ParentIncident"] = TaskAPI.Incident;
                                taskContractAPI["AutoBusinessKey"] = key;
                                taskContractAPI["BlankVlue"] = _storeid;
                                taskContractAPI["Actions"] = "ChangeContract";
                                taskContractAPI["Alert"] = "此门店需要进行签署以下合同，请通知相关人员签署合同并提交总部 （可进入系统批量处理）：\n\r合同终止及三方转移合同";
                                taskContractAPI.InitAutoTask(contractApplicationNo);
                                taskContractAPI.Summary = "合同信息完善/" + TaskHelper.getSummary(TaskAPI.Summary);
                                taskContractAPI["MailSubject"] = string.Format("授权号：{0} -- {1}）", store.AuthID, store.StoreType);
                                taskContractAPI.SetStoreDataChangeRecipient(storeMasterData.AreaName, storeMasterData.ProvinceName, "Contract");

                                //门店关闭降级都要签终止合同协议
                                //签终止协议。
                                var contract = ContractService.GetContractByStoreID(_storeid) ?? new t_smd_Contract
                                {
                                    AuthID = store.AuthID,
                                    StoreID = store.StoreID
                                };
                                var contractCancel = ContractService.GetContractCancel(contract);
                                var oldContract = ContractService.GetOldContract(contract);
                                oldContract.StoreCancelContractType = contract.StoreContractType;
                                Storage.Save(Storage.Context3, oldContract);
                                Storage.Save(Storage.Context3, contractCancel);


                                if ((storeMasterData.RequestRemark == "Downgraded" && storeMasterData.StoreType.Contains("IS")) ||
                                    store.StoreStatus == "关闭")
                                {
                                    (t_smd_Contract._StoreID == store.StoreID).Delete<t_smd_Contract>(Storage.Context3);
                                }
                                else
                                {
                                    contract = ContractService.GetNewContract(contract, true);
                                    contract.StoreNature = "新签";
                                    Storage.Save(Storage.Context3, contract);
                                }


                                if (taskContractAPI.Send())
                                {
                                    t_Assessment ass = taskContractAPI.InitAutoAssessment();
                                    Storage.Save(Storage.Context1, ass);

                                    BusinessService.SaveChildProcess(taskContractAPI, ass, "active");
                                }
                            }
                            #endregion
                        }
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                return_msg = ex.Message.Replace("\"", "\\\"");
                Logging.GetLogger().Error("调用DegradeStore.aspx方法Send_Click出错：" + ex);
                flag = false;
            }
            return flag;
        }

        #region 展示只读数据

        private void ViewData(t_smd_Store store, List<string> AssessmentID)
        {

            var storeMasterData =
                (t_StoreMasterData._Process == TaskAPI.Process & t_StoreMasterData._Incident == TaskAPI.Incident)
                    .ListFirst<t_StoreMasterData>();
            var changeLogs = ChangeLogService.GetLastChangeLogs(AssessmentID);


            tb_CloseDate.Visible = false;
            tb_CloseReason.Visible = false;
            tb_CloseType.Visible = false;


            if (storeMasterData.NewFitment.Contains("降级"))
            {
                l_IsDowngraded.Text = "降级";
                var tStoreDataChangeLog = changeLogs.FirstOrDefault(t => t.FieldName == "StoreType");
                if (tStoreDataChangeLog != null)
                    l_BeforeDowngradedType.Text = tStoreDataChangeLog.BeforeValue;

                var newStore = DataHelper<t_smd_Store>.Reload(store, changeLogs);
                newStore.EapproveSN = storeMasterData.SerialNumber;
                l_CloseDate.Text = newStore.CloseDate.HasValue ? newStore.CloseDate.Value.ToString("yyyy-MM-dd") : "";
                l_CloseReason.Text = newStore.CloseReason;
                l_CloseType.Text = newStore.CloseType;

            }
            else
            {
                var newStore = DataHelper<t_smd_Store>.Reload(store, changeLogs);
                newStore.EapproveSN = storeMasterData.SerialNumber;
                l_IsDowngraded.Text = "关闭";
                l_CloseDate.Text = newStore.CloseDate.HasValue ? newStore.CloseDate.Value.ToString("yyyy-MM-dd") : "";
                l_CloseReason.Text = newStore.CloseReason;
                l_CloseType.Text = newStore.CloseType;

                jj.Visible = false;
            }

        }

        #endregion

        protected void btn_submit_Click(object sender, EventArgs e)
        {
            string return_msg = string.Empty;
            if (Send(ref return_msg))
            {
                btn_submit.Visible = false;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "info_prompt", "$.jBox.prompt('操作成功！','提示', 'info', { closed: function () { window.opener.reload(); closeWin(); } });", true);
                return;
            }
            else
            {
                return_msg = string.IsNullOrEmpty(return_msg) ? Resources.Global.C_00_Failed : return_msg;
                ScriptManager.RegisterStartupScript(this, this.GetType(), "info_tip", "$.jBox.prompt('" + return_msg + "','提示', 'info');", true);
                return;
            }
        }
    }
}